/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-06-04
 * Time: 13:52
 */
public class HushBucket {

    public double LoadFactor = 0.75;//负载因子

    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.val = val;
            this.key = key;
        }
    }

    //计算当前负载因子
    private double getLoadFactor() {
        return size * 1.0 / array.length;
    }

    //扩容
    private void resize() {
        //每个元素都需要重新哈希
        Node[] newArr = new Node[array.length * 2];
        for (int i = 0; i < array.length; i++) {
            Node cur = array[i];
            //遍历链表
            while (cur != null) {
                int newIndex = cur.key % newArr.length;
                Node cN = cur.next;
                cur.next = newArr[newIndex];
                newArr[newIndex] = cur;
                cur = cN;
            }
        }
        array = newArr;
    }

    public int size;//元素个数
    public Node[] array;//数组

    public HushBucket() {
        this.array = new Node[10];
    }

    public void put(int key, int val) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                cur.val = val;
                return;//key不能重复,插入重复的key相当于更新val
            }
            cur = cur.next;
        }
        //
        Node newNode = new Node(key, val);
        newNode.next = array[index];
        array[index] = newNode;
        size++;
        if (getLoadFactor() >= LoadFactor) {
            //扩容
            resize();
        }
    }

    //获取key值的val
    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while (cur != null) {
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }

}
